// 流动墙体材质
class WallTrailMaterialProperty {
  isConstant;
  definitionChanged;
  _time;
  type;
  image;
  source;
  _color;
  _colorSubscription;
  duration;
  Cesium;

  constructor(Cesium, image, color = "#ff0000", duration = 20000) {
    this.Cesium = Cesium;
    this.isConstant = false;
    this.definitionChanged = new this.Cesium.Event();
    this._color = undefined;
    this._colorSubscription = undefined;
    this._time = new Date().getTime();

    this.color = color;
    this.duration = duration;
    // 类型（会自动加载到cesium中）
    this.type = "WallTrail";

    this.image = image || "./static/images/edge.png";

    // 着色器
    this.source = `czm_material czm_getMaterial(czm_materialInput materialInput)
        {
          czm_material material = czm_getDefaultMaterial(materialInput);
          vec2 st = materialInput.st;
          vec4 colorImage = texture2D(image, vec2(fract(st.s - time), st.t));
          material.alpha = colorImage.a * color.a;
          material.diffuse = (colorImage.rgb+color.rgb)/2.0;
          return material;
        }`;

    this.addMaterial();
  }

  getType() {
    return "WallTrail";
  }

  getValue(time, result) {
    if (!this.Cesium.defined(result)) {
      result = {};
    }

    result.color = this.Cesium.Property.getValueOrClonedDefault(
      this._color,
      time,
      this.Cesium.Color.WHITE,
      result.color
    );
    result.image = this.image;
    result.time =
      ((new Date().getTime() - this._time) % this.duration) / this.duration;

    return result;
  }

  equals(other) {
    return (
      this === other ||
      (other instanceof WallTrailMaterialProperty &&
        this.Cesium.Property.equals(this._color, other._color))
    );
  }

  addMaterial() {
    this.Cesium.Material._materialCache.addMaterial(this.type, {
      fabric: {
        type: this.type,
        uniforms: {
          color: new this.Cesium.Color(1, 0, 0, 0.5),
          image: this.image,
          time: -10,
        },
        source: this.source,
      },

      translucent: true,
    });
  }
}

// 流动墙体类
export class WallTrail {
  viewer;
  Cesium;
  position;
  id;
  color;
  duration;

  constructor(
    position,
    id,
    color = "#00ff00",
    duration = 1000,
    image,
    viewer,
    Cesium
  ) {
    this.viewer = viewer;
    this.Cesium = Cesium || window.Cesium;
    this.id = id;
    this.duration = duration || 1000;
    this.color = color || "#00ff00";
    this.position = position;
    this.image = image;
  }

  init() {
    const self = this;
    this.WallTrailEntity = this.viewer.entities.add({
      id: self.id,
      name: self.id,
      wall: {
        clampToGround: true,
        material: new WallTrailMaterialProperty(self.Cesium, self.image),
        positions: self.Cesium.Cartesian3.fromDegreesArrayHeights(
          self.position
        ),
      },
      show: true,
    });
  }

  remove() {
    this.viewer.entities.remove(this.WallTrailEntity);
  }
}
